package net.caixiaomi.info.ui.mine;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.PayWayAdapter;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.BaseAlertDialog;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.model.AllPaymentWithRecharge;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.PayWayItem;
import net.caixiaomi.info.model.PaymentAppModel;
import net.caixiaomi.info.model.RechargeUserLimit;
import net.caixiaomi.info.model.UserInfoModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.dialog.RedPocketDialog;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.info.widgets.DefLoading;

import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 充值
 */

public class RechargeActivity extends BaseActivity implements View.OnClickListener, TextWatcher, BaseQuickAdapter.OnItemClickListener {

    @BindView(R.id.account)
    TextView mAccount;

    @BindView(R.id.price)
    EditText mPrice;
    /**
     * 固定金额容器
     */
    @BindView(R.id.container)
    LinearLayout mMoneyContainer;

    @BindView(android.R.id.list)
    RecyclerView mListView;

    @BindView(R.id.progress)
    CircularProgressBar mProgress;

    @BindView(R.id.btn_pay)
    View mBtnPay;

    @BindView(R.id.label)
    TextView mLabel;

    private PayWayAdapter mAdapter;
    private String mPayLogId = "";
    private boolean isThirdPay = false;
    private boolean mPayFinished = false;
    private boolean mRechargeAct = false;
    private RechargeUserLimit mRechargeUserLimit;
    private boolean mInvalideRechareAction = false;

    private boolean isDisabled;
    private String toastPrice;


    /**
     * 现只支持微信支付
     */
    @OnClick(R.id.btn_pay)
    void toPay() {
        String price = mPrice.getText().toString().trim();
        if (TextUtils.isEmpty(price)) {
            ToastUtil.s(R.string.C_INPUT_RECHARGE_MONEY);
            return;
        }
        if (mAdapter.getData().isEmpty())
            return;

        AppHelper.sendStatistics("czzhifu", new String[]{getString(R.string.C_TERMINAL)}, new String[]{Build.BOARD});

        mLoading.show();
        mPayFinished = false;
        String payCode = "";
        Iterator<PayWayItem> iterator = mAdapter.getData().iterator();
        while (iterator.hasNext()) {
            PayWayItem next = iterator.next();
            if (next.isSelected()) {
                payCode = next.getPayCode();
                break;
            }
        }
        JSONObject params = new JSONObject();
        params.put("payCode", payCode);
        params.put("totalAmount", price);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<PaymentAppModel>> recharge = requestService.recharge(params);
        recharge.enqueue(new ResponseCallback<BaseCallModel<PaymentAppModel>>(this) {
            @Override
            public void onSuccess(BaseCallModel<PaymentAppModel> data) {
                mLoading.dismiss();
                PaymentAppModel model = data.data;
                mPayLogId = model.getPayLogId();
                mBtnPay.setEnabled(false);
                isThirdPay = true;
                mProgress.setVisibility(View.VISIBLE);
                startThirdPay(model.getPayUrl());
            }

            @Override
            public void onFail(ResponseError error) {
                mLoading.dismiss();
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                }
            }

            @Override
            public void onError() {
                mLoading.dismiss();
            }
        });
    }

    @Override
    protected int layout() {
        return R.layout.act_recharge;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            String data = getIntent().getStringExtra("data");
            String price = "";
            if (!TextUtils.isEmpty(data)) {
                JSONObject object = JSON.parseObject(data);
                price = object.getString("price");
            }

            isDisabled=TextUtils.equals(getIntent().getStringExtra("isDisabled"),"1");
            toastPrice=getIntent().getStringExtra("toastPrice");
            if(isDisabled){
                mMoneyContainer.setVisibility(View.GONE);
                mPrice.setFocusable(false);
                mPrice.setFocusableInTouchMode(false);
                mPrice.setCursorVisible(false);
            }

            mLoading = new DefLoading(this);
            mPrice.addTextChangedListener(this);
            mPrice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AppHelper.sendStatistics("czshurujine");
                }
            });
            if (!TextUtils.isEmpty(price)) {
                mPrice.setText(price);
                mPrice.setSelection(price.length());
            }

            mListView.setLayoutManager(new LinearLayoutManager(this));
            mAdapter = new PayWayAdapter(R.layout.item_pay_way);
            mAdapter.setOnItemClickListener(this);
            mListView.setAdapter(mAdapter);

            UserInfoModel userInfo = CommonApp.getUserInfo();

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(getString(R.string.C_CURRENT_ACCOUNT)).append(": ").append(userInfo.getMobile()).append("\n");
            stringBuilder.append(getString(R.string.C_CURRENT_BALANCE)).append(": ").append(!TextUtils.isEmpty(userInfo.getTotalMoney()) ? userInfo.getTotalMoney() : "0.00").append(getString(R.string.C_MONEY));
            mAccount.setText(stringBuilder);

            String[] moneyArray = getResources().getStringArray(R.array.C_RECHARGE_MONEY_ARRAY);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
            for (int index = 0; index < moneyArray.length; index++) {
                String money = moneyArray[index];
                TextView textView = new TextView(this);
                textView.setText(money);
                textView.setBackgroundResource(R.drawable.bg_white_stroke_corner);
                textView.setTextColor(ContextCompat.getColor(this, R.color.black));
                textView.setTextSize(14);
                textView.setGravity(Gravity.CENTER);
                textView.setPadding(0, (int) getResources().getDimension(R.dimen.padding_12), 0, (int) getResources().getDimension(R.dimen.padding_12));
                textView.setOnClickListener(this);
                if (index != moneyArray.length - 1) {
                    layoutParams.rightMargin = (int) getResources().getDimension(R.dimen.padding_12);
                }
                mMoneyContainer.addView(textView, layoutParams);
            }
            loadPayWay();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshData();
        if (isThirdPay) {
            mCountDownTimer.start();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCountDownTimer.cancel();
        mCountDownTimer = null;

    }

    private void refreshData() {
        JSONObject params = new JSONObject();
        params.put("time", String.valueOf(System.currentTimeMillis()));
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<UserInfoModel>> userInfoExceptPass = requestService.userInfoExceptPass(params);
        userInfoExceptPass.enqueue(new ResponseCallback<BaseCallModel<UserInfoModel>>(this) {
            @Override
            public void onSuccess(BaseCallModel<UserInfoModel> data) {
                //更新userInfo数据
                UserInfoModel userInfo = data.data;
                userInfo.setToken(CommonApp.getToken());
                CommonApp.setUserInfo(userInfo);

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(getString(R.string.C_CURRENT_ACCOUNT)).append(": ").append(userInfo.getMobile()).append("\n");
                stringBuilder.append(getString(R.string.C_CURRENT_BALANCE)).append(": ").append(!TextUtils.isEmpty(userInfo.getTotalMoney()) ? userInfo.getTotalMoney() : "0.00").append(getString(R.string.C_MONEY));
                mAccount.setText(stringBuilder);

            }

            @Override
            public void onFail(ResponseError error) {

            }

            @Override
            public void onError() {
            }
        });
    }


    private void loadPayWay() {
        JSONObject params = new JSONObject();
        params.put("time", System.currentTimeMillis());
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<AllPaymentWithRecharge>> baseCallModelCall = requestService.allPaymentWithRecharge(params);
        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel<AllPaymentWithRecharge>>(this) {
            @Override
            public void onSuccess(BaseCallModel<AllPaymentWithRecharge> data) {
                try {
                    AllPaymentWithRecharge model = data.data;
                    List<PayWayItem> paymentList = model.getPaymentList();
                    if (!paymentList.isEmpty()) {
                        paymentList.get(0).setSelected(true);
                    }
                    mAdapter.setNewData(paymentList);
                    mRechargeAct = TextUtils.equals(model.getIsHaveRechargeAct(), "1");
                    mRechargeUserLimit = model.getRechargeUser();
                    updateLable(mPrice.getText().toString().trim());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFail(ResponseError error) {
            }

            @Override
            public void onError() {
            }
        });
    }

    private void paymentQuery(String payLogId) {
        if (mPayFinished)
            return;
        JSONObject params = new JSONObject();
        params.put("payLogId", payLogId);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel> paymentQuery = requestService.paymentQuery(params);
        paymentQuery.enqueue(new ResponseCallback<BaseCallModel>(this) {
            @Override
            public void onSuccess(BaseCallModel data) {
                if (mPayFinished)
                    return;
                mPayFinished = true;
                mProgress.setVisibility(View.GONE);
                mBtnPay.setEnabled(true);
                ToastUtil.s(data.msg);
                finish();
                if (mRechargeAct && mInvalideRechareAction) {
//                    RedPocketDialog dialog = new RedPocketDialog();
//                    Bundle bundle = new Bundle();
//                    bundle.putString("payLogId", mPayLogId);
//                    bundle.putBoolean("isNewUser", TextUtils.equals("0", mRechargeUserLimit.getOldUserBz()));
//                    dialog.setArguments(bundle);
//                    dialog.show(getSupportFragmentManager(), dialog.getClass().getName());
                } else {
                    onBackPressed();
                }
            }

            @Override
            public void onFail(ResponseError error) {
                if (mPayFinished)
                    return;
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    if (error.getCode() == 304035) {//融宝支付失败
                        mBtnPay.setEnabled(true);
                        mProgress.setVisibility(View.GONE);
                        mCountDownTimer.cancel();
                        isThirdPay = false;
                        mPayFinished = true;
                        showDialogNotice(error.getMessage());
                    }
                }
            }

            @Override
            public void onError() {
            }
        });
    }

    @Override
    public void onClick(View v) {
        AppHelper.sendStatistics("czgudingjine");
        TextView textView = (TextView) v;
        String text = textView.getText().toString();
        mPrice.setText(text);
        mPrice.setSelection(text.length());
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String text = s.toString().trim();
        if(text.startsWith("0")){
            mPrice.setText("");
            return;
        }
        boolean isEmpty = TextUtils.isEmpty(text);
        mPrice.setSelected(isEmpty);
        updateLable(text);

    }

    private void updateLable(String text) {
        boolean isEmpty = TextUtils.isEmpty(text);
        if (mRechargeAct) {
            mInvalideRechareAction = false;
            if (!isEmpty) {
                if (text.length() < 2) {
                    mLabel.setVisibility(View.GONE);
                    return;
                }
                mLabel.setVisibility(View.VISIBLE);
//                int price = Integer.valueOf(text);
                long price=Long.valueOf(text);
                List<RechargeUserLimit.DonationPrice> donationPriceList = mRechargeUserLimit.getDonationPriceList();
                for (int index = donationPriceList.size() - 1; index >= 0; index--) {
                    RechargeUserLimit.DonationPrice donationPrice = donationPriceList.get(index);
                    if (price >= Long.valueOf(donationPrice.getMinRechargeAmount())) {
                        mInvalideRechareAction = true;
                        if(!TextUtils.isEmpty(toastPrice)) {
                            mLabel.setText(toastPrice);
                        }else{
                            mLabel.setText("");
                            mLabel.setVisibility(View.GONE);
                        }
//                        if(isDisabled){
//                            mLabel.setText(getString(R.string.C_RECHARGE_GIVE_BOUND_LABLE, toastPrice));
//                        }else{
//                            mLabel.setText(getString(R.string.C_RECHARGE_GIVE_BOUND_LABLE, donationPrice.getDonationAmount()));
//
//                        }

                        break;
                    }
                }
            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        try {
            PayWayItem item = mAdapter.getData().get(position);
            if (item.isSelected())
                return;
            Iterator<PayWayItem> iterator = mAdapter.getData().iterator();
            while (iterator.hasNext()) {
                PayWayItem next = iterator.next();
                next.setSelected(false);
            }
            mAdapter.getData().get(position).setSelected(true);
            mAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showDialogNotice(String message) {
        BaseAlertDialog dialog = new BaseAlertDialog(this);
        dialog.setMessage(message);
        dialog.setPositiveButton(R.string.C_I_KNOW, null);
        dialog.show();
    }

    private CountDownTimer mCountDownTimer = new CountDownTimer(5 * 1000, 3000) {
        @Override
        public void onTick(long millisUntilFinished) {
            paymentQuery(mPayLogId);
        }

        @Override
        public void onFinish() {
            if (mPayFinished)
                return;
            mPayFinished = true;
            mProgress.setVisibility(View.GONE);
            mBtnPay.setEnabled(true);
            isThirdPay = false;
            showDialogNotice(getString(R.string.C_ORDER_SEARCH_FAIL));
        }
    };

    private void startThirdPay(String payUrl) {
        Uri uri = Uri.parse(payUrl);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }
}
